package com.juzipi.framework.web.service;

import com.juzipi.common.constant.Constants;
import com.juzipi.common.constant.properties.PropertiesVariable;
import com.juzipi.common.utils.StringUtils;
import com.juzipi.inter.domain.LoginUser;
import com.juzipi.inter.pojo.Role;
import com.juzipi.inter.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MyUserDetailsService implements UserDetailsService {


    @Autowired
    private LoginUserService loginUserService;


    /**
     * 登录时会进入这里
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (StringUtils.isEmpty(username)) {
            throw new InternalAuthenticationServiceException("账号【" + username + "】为空");
        }
        //根据用户名获取用户信息
        User user = loginUserService.checkUser(username);
        if (StringUtils.isNull(user)) {
            throw new InternalAuthenticationServiceException("用户【" + username + "】不存在");
        }
        //用户状态
        if (!Constants.USER_STATUS.equals(user.getNonDisable())) {
            throw new DisabledException("用户【" + username + "】已被禁用");
        }
        //用户是否禁用
        if (!Constants.USER_NON_LOCKED.equals(user.getNonLocked())) {
            //如果锁定时间已达到20分钟
            if (!loginUserService.checkLockedTime(user)) {
                throw new LockedException("用户【" + username + "】已被锁定，请【" + PropertiesVariable.userTimesLock + "】分钟后再尝试登录");
            }
        }

        //等于是包装一下
        UserDetails loginUser = createLoginUser(user);
        return loginUser;
    }
    private UserDetails createLoginUser(User user) {
        //获取到用户的角色
        List<Role> roles = loginUserService.queryUserRoleList(user.getRoleId());
        //登录的时候把user的数据库里的权限设置进loginUser
        LoginUser loginUser = new LoginUser(user, roles);
        return loginUser;
    }
}
